package com.example.demo6.Controller;

import com.auth0.jwt.JWT;
import com.example.demo6.Service.UserService;
import com.example.demo6.entity.LoginUser;
import com.example.demo6.entity.User;
import com.example.demo6.utils.JWTUtils;
import com.example.demo6.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @PostMapping("/login")
    public ServerResponse<String> login(@RequestBody LoginUser loginUser){
        String storeCode= (String) redisTemplate.opsForValue().get("captcha_codes:"+loginUser.getUuid());
        System.out.println(storeCode+loginUser.toString());
        if(loginUser.getCode().equals(storeCode)){
            User u=userService.getUser(loginUser);
            if(u!=null){
                Map<String,String> map=new HashMap<>();
                map.put("userid",u.getUserId()+"");
                map.put("username",u.getUserName());
                String token= JWTUtils.getToken(map);
                redisTemplate.delete(storeCode);
                return  ServerResponse.createBySuccess(200,token,"登录成功");
            }
            return  ServerResponse.createBySuccess(500,"","账号或密码错误");
        }else {
            return ServerResponse.createBySuccess(500,"","验证码错误");
        }

    }
@GetMapping("/getInfo")
    public  ServerResponse<User> getInfo(HttpServletRequest request){
        String token=request.getHeader("Authorization");
    System.out.println(token+"  ");
    String id = JWT.decode(token.substring(token.lastIndexOf(" ")+1)).getClaim("userid").asString();
    User user=userService.getUserById(Integer.parseInt(id));
    return ServerResponse.createBySuccess(200,user,"查询成功");
}
//
//@GetMapping("/{userId}/avatar-url")
//public ServerResponse<String> getAvatarUrl(@PathVariable Integer userId) throws Exception {
//    String avatarUrl = userService.getAvatarById(userId);
//    if (avatarUrl != null) {
//        return ServerResponse.createBySuccess(200, avatarUrl, "头像 URL 获取成功");
//    } else {
//        return ServerResponse.createByFail(404, "头像未找到");
//    }
//}
}